
import { defineStore } from 'pinia'
import { ref } from "vue";
import type { LoginRes } from "@/interface/LoginRes";
import { loginOutApi } from "@/controller/UserApi";
import { useRouter } from "vue-router"
import { message } from "ant-design-vue";
import type {ChatModel} from "@/interface/ChatModel";
import { useSocket } from "@/stores/Socket"

export const useLoginStore = defineStore('loginStore', () => {

  let loginInfo = ref({} as LoginRes);

  let socket = useSocket();


  const router = useRouter();

  function loginOut() {
    loginOutApi().then(res => {
      if (res.code == 200) {
        if (socket.webSocket) {
          if ( loginInfo.value.user && loginInfo.value.user.user.id) {
            socket.send({ cmd: 199 , userId : loginInfo.value.user.user.id } as ChatModel);
          }
          socket.destroy();
        }
        loginInfo.value = {} as LoginRes;
        message.success("退出成功");
        router.push("/");
      }
    });
  }

  return { loginInfo , loginOut  }
},{ persist: true});
